const createDao = require('../dao/create');

const powerService = require('./power');
const { createUserJwtToken } = require('../util/server_jwt');

const createCardkey = require('../util/create_cardkey');

const createService = {
    // 创建副卡密
    async createSubCard(uid, userTypeId, name, endAt) {
        let result;
        let card;
        // 鉴权
        try {
            result = await powerService.checkPower(userTypeId, "创建副卡密");
            if (!result.data) {
                return { code: 403, msg: "无权限进行此操作", data: null };
            }
        } catch (err) {
            return { code: 500, msg: "服务器错误", data: null };
        }
        // 调用数据层
        try {
            // 死循环直到插入成功
            while (true) {
                card = 'sk-' + createCardkey();
                result = await createDao.createSubCard(uid, name, card, endAt);
                if (result.insertId) {
                    break;
                }
            }
            return { code: 200, msg: "创建副卡密成功", data: { card } };
        } catch (err) {
            return { code: 500, msg: "服务器错误", data: null };
        }
    },
    // 创建用户卡密
    async createUserCard(uid, userTypeId, name, endAt) {
        let result;
        let card;
        // 鉴权
        try {
            result = await powerService.checkPower(userTypeId, "创建用户卡密");
            if (!result.data) {
                return { code: 403, msg: "无权限进行此操作", data: null };
            }
        } catch (err) {
            return { code: 500, msg: "服务器错误", data: null };
        }
        // 查看当前卡密是否还能使用
        try {
            result = await powerService.getUser(uid);
            if (!result.data) {
                return { code: 403, msg: "该用户已被冻结", data: null };
            }
        } catch (err) {
            return { code: 500, msg: "服务器错误", data: null };
        }
        // 调用数据层
        try {
            // 死循环直到插入成功
            while (true) {
                card = 'sk-' + createCardkey();
                result = await createDao.createUserCard(uid, name, card, endAt);
                if (result.insertId) {
                    break;
                }
            }
            return { code: 200, msg: "创建用户卡密成功", data: { card } };
        } catch (err) {
            return { code: 500, msg: "服务器错误", data: null };
        }
    },
};

module.exports = createService;
